<script lang="ts" setup>
import { ref, defineEmits } from 'vue'
import { useVbenModal } from '@vben/common-ui'
import { message, Button, Table, Input, DatePicker, Modal as AModal } from 'ant-design-vue'
import type { TableColumnsType } from 'ant-design-vue'
import { h } from 'vue'
import { addGoodsDeliveryTimeLog } from '#/api/goodsDeliveryTimeLog'
import SelectPurchase from './selectPurchase.vue'

interface FormDataItem {
  goods_purchase_sn: string
  goods_no: string
  price: number | string
  go_dead_line: string
  expected_completion_date: string
  reason: string
  id?: number
  [key: string]: any
}

const emit = defineEmits(['fetchData'])

// 表单数据
const formData = ref<FormDataItem[]>([])
const submitLoading = ref(false)
const title = ref('批量修改交货日期')

// 表格列配置
const columns: TableColumnsType = [
  { title: '采购单号', dataIndex: 'goods_purchase_sn', width: 140, align: 'center' as const },
  { title: '货号', dataIndex: 'goods_no', width: 110, align: 'center' as const },
  { title: '采购价', dataIndex: 'price', width: 120, align: 'center' as const },
  { title: '商企要求交期', dataIndex: 'go_dead_line', width: 120, align: 'center' as const },
  { title: '交货日期', dataIndex: 'expected_completion_date', width: 150, align: 'center' as const, key: 'date' },
  { title: '原因', dataIndex: 'reason', align: 'center' as const, key: 'reason' },
  { title: '操作', dataIndex: 'operation', width: 100, align: 'center' as const, key: 'operation' },
]

// 打开选择采购单弹窗
const handleOpenSelectPurchase = () => {
  SelectPurchaseModalApi.setData({}).open()
}

// 处理选择采购单的回调
const handleSelectConfirm = (selectedRows: any[]) => {
  if (selectedRows.length === 0) {
    return
  }
  
  // 添加到表单数据 - 保留所有原始字段，只添加reason字段
  const newData = selectedRows.map(row => ({
    ...row, // 保留所有原始字段（包括goods_purchase_detail_id）
    reason: '', // 添加原因字段
  }))
  
  formData.value = [...formData.value, ...newData]
}

// 删除行
const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
}

// 更新日期
const handleDateChange = (_date: any, dateString: string, index: number) => {
  if (formData.value[index]) {
    formData.value[index].expected_completion_date = dateString
  }
}

// 提交表单
const handleSubmit = async () => {
  if (formData.value.length === 0) {
    message.warning('请先添加采购单')
    return
  }
  
  // 验证必填字段
  const hasEmptyReason = formData.value.some(item => !item.reason || item.reason.trim() === '')
  if (hasEmptyReason) {
    message.warning('请填写所有采购单的修改原因')
    return
  }
  
  const hasEmptyDate = formData.value.some(item => !item.expected_completion_date)
  if (hasEmptyDate) {
    message.warning('请选择所有采购单的交货日期')
    return
  }
  
  submitLoading.value = true
  
  try {
    const res = await addGoodsDeliveryTimeLog({
      formData: formData.value,
    })
    
    // 检查是否需要确认
    if (res.code === 201) {
      submitLoading.value = false
      showConfirmModal(res.data || [])
      return
    }
    
    message.success('提交成功')
    modalApi.close()
    emit('fetchData')
  } catch (error: any) {
    if (error.code === 201) {
      submitLoading.value = false
      showConfirmModal(error.data || [])
      return
    }
  } finally {
    submitLoading.value = false
  }
}

// 显示确认变更弹窗
const showConfirmModal = (confirmFormData: any[]) => {
  // 构建确认内容
  const content = h('div', { class: 'confirm-content' }, [
    ...confirmFormData.map((item) => 
      h('div', { class: 'mb-4' }, [
        h('div', { class: 'font-bold mb-2' }, `单号：${item.goods_purchase_sn}，货号：${item.goods_no}`),
        h('div', { class: 'pl-4' }, [
          ...item.updateData.map((item2: any) =>
            h('div', { class: 'mb-2' }, [
              h('div', { class: 'text-gray-600' }, `${item2.fieldName}：`),
              h('div', {}, `改前: ${item2.origin}`),
              h('div', { class: 'text-red-500' }, `改后: ${item2.destination}`),
            ])
          ),
        ]),
      ])
    ),
  ])
  
  AModal.confirm({
    title: '存在货期变更确认',
    content,
    width: '80%',
    okText: '确认继续修改并提交价格审批',
    cancelText: '取消',
    async onOk() {
      try {
        await addGoodsDeliveryTimeLog({
          formData: formData.value,
          is_confirm: true,
        })
        
        message.success('提交成功')
        modalApi.close()
        emit('fetchData')
      } catch (error) {
        console.error('提交失败:', error)
        return Promise.reject(error)
      }
    },
  })
}

// 关闭弹窗
const handleClose = () => {
  modalApi.close()
}

const [Modal, modalApi] = useVbenModal({
  class: 'w-[90%]',
  appendToMain: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<Record<string, any>>()
      if (data && data.info && data.info.id) {
        title.value = '编辑'
      } else {
        title.value = '批量修改交货日期'
        formData.value = []
      }
    }
  },
})

// 二级弹窗 - 选择采购单
const [SelectPurchaseModal, SelectPurchaseModalApi] = useVbenModal({
  connectedComponent: SelectPurchase,
})
</script>

<template>
  <Modal :title="title">
    <div class="p-4">
      <div class="mb-4">
        <Button type="primary" @click="handleOpenSelectPurchase">
          批量添加采购单号
        </Button>
      </div>

      <Table
        :columns="columns"
        :data-source="formData"
        :pagination="false"
        :scroll="{ x: 'max-content' }"
        row-key="id"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'date'">
            <DatePicker
              :value="record.expected_completion_date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择货期"
              @change="(date, dateString) => handleDateChange(date, dateString, index)"
            />
          </template>
          <template v-else-if="column.key === 'reason'">
            <Input v-model:value="record.reason" placeholder="请输入原因" />
          </template>
          <template v-else-if="column.key === 'operation'">
            <Button type="link" danger @click="handleDelete(index)">删除</Button>
          </template>
        </template>
      </Table>
    </div>

    <template #prepend-footer>
      <Button @click="handleClose()">取消</Button>
      <Button type="primary" :loading="submitLoading" @click="handleSubmit">
        发起审批
      </Button>
    </template>

    <!-- 二级弹窗：选择采购单 -->
    <SelectPurchaseModal @select-confirm="handleSelectConfirm" />
  </Modal>
</template>

<style scoped lang="scss">
:deep(.ant-picker) {
  width: 100%;
}
</style>
